<?php

namespace Acme\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Acme\UserBundle\Helper\UploadHandler;
use Acme\PersonBundle\Entity\Personimage;
use Acme\PinnwandBundle\Entity\Pinnwand;
use Acme\PinnwandBundle\Entity\Pinnwandgalerie;
use Doctrine\ORM\EntityRepository;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Validator\Constraints\DateTime;

/**
 * @Route("/auth/security")
 */
class SecurityController extends Controller {
	private $limitRange = 10;
	
	/**
	 * @Route("/login", name="_security_start")
	 * @Template()
	 */
	public function loginAction() {
		$request = $this->getRequest ();
		
		// echo $request->getUri(); exit;
		
		$session = $request->getSession ();
		// get the login error if there is one
		if ($request->attributes->has ( SecurityContext::AUTHENTICATION_ERROR )) {
			$error = $request->attributes->get ( SecurityContext::AUTHENTICATION_ERROR );
		} else {
			$error = $session->get ( SecurityContext::AUTHENTICATION_ERROR );
			$session->set ( SecurityContext::AUTHENTICATION_ERROR, '' );
		}
		
		return array (
				'last_username' => $request->getSession ()->get ( SecurityContext::LAST_USERNAME ),
				'error' => $error 
		);
	}
	
	/**
	 * @Route("/login_check", name="_secure_check")
	 */
	public function securityCheckAction() {
	}
	
	/**
	 * @Route("/admin", name="login_admin")
	 */
	public function adminAction() {
		
		// The security layer will intercept this request
		
		// if($request->isMethod('POST')){
		// }
		// return new Response('<html><body>Hello!</body></html>');
	}
	
	/**
	 * @Route("/logout", name="_secure_logout")
	 */
	public function logoutAction() {
		// The security layer will intercept this request
	}
	
	/**
	 * @Route("/index", name="login_index")
	 * @Template()
	 */
	public function indexAction() {
		$limitFrom = 0;
		if ($this->getRequest ()->get ( 'limitFrom' )) {
			$limitFrom = $this->getRequest ()->get ( 'limitFrom' );
		}
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$arr_data ["pinnwands"] = $this->getPinnwand ( $limitFrom );
		$arr_data ["pinnwandhistory"] = $this->getHistoryLink ( $limitFrom );
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'pinnwands' => $arr_data ["pinnwands"],
				'pinnwandhistory' => $arr_data ["pinnwandhistory"],
				'persons' => $arr_data ["persons"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'usersinformation' => $arr_data ["usersinformation"] 
		// 'target' => $this->getRequest()->getSession()->get('target')
				);
	}
	
	/**
	 * @Route("/uploadimages/{typ}", name="upload_images")
	 * @Template()
	 */
	public function uploadImagesAction($typ = "") {
		// if ($this->container->has('profiler')){
		// $this->container->get('profiler')->disable();
		// }
		if ($this->getRequest ()->server->get ( 'HTTPS' )) {
			$prot = 'https://';
		} else {
			$prot = 'http://';
		}
		
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/personal/';
		if (! is_dir ( $path )) {
			mkdir ( $path );
		}
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/personal/' . $usr->getUsername () . '/';
		if (! is_dir ( $path )) {
			mkdir ( $path );
		}
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/personal/' . $usr->getUsername () . '/files/';
		if (! is_dir ( $path )) {
			mkdir ( $path );
		}
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/personal/' . $usr->getUsername () . '/files/profilbild/';
		if (! is_dir ( $path )) {
			mkdir ( $path );
		}
		
		if ($typ != "") {
			$path = str_replace ( '-', '/', $typ ) . '/';
			// $path = 'pinnwand/' . $usr->getUsername() . '/' . $typ . '/files/';
			$delete_url = $prot . $this->getRequest ()->server->get ( 'SERVER_NAME' ) . '/auth/security/delpersonal/' . $typ;
		} else {
			$path = 'personal/' . $usr->getUsername () . '/files/';
			$delete_url = $prot . $this->getRequest ()->server->get ( 'SERVER_NAME' ) . '/auth/security/delpersonal';
		}
		
		$url = $prot . $this->getRequest ()->server->get ( 'SERVER_NAME' ) . '/' . $path;
		$dir = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/' . $path;
		
		$options = array (
				'upload_dir' => $dir,
				'upload_url' => $url,
				'delete_url' => $delete_url 
		);
		$upload_handler = new UploadHandler ( $options );
		
		if ($typ != "") {
			return array ();
		}
		
		// store image
		// $usr = $this->container->get('security.context')->getToken()->getUser();
		foreach ( $upload_handler->_filename as $filename ) {
			$personimage = new Personimage ();
			$personimage->setImage ( $filename );
			$personimage->setPath ( $path );
			$personimage->setPerson ( $usr->getId () );
			$personimage->setTitle ( '' );
			$personimage->setDescription ( '' );
			$personimage->setStandart ( 0 );
			$em = $this->getDoctrine ()->getManager ();
			$em->persist ( $personimage );
			$em->flush ();
			// $personimage->getId();
		}
		
		return array ();
	}
	
	/**
	 * @Route("/delpersonal/{typ}", name="delete_personal")
	 * @Template()
	 */
	public function delPersonalAction($typ = "") {
		if ($this->getRequest ()->server->get ( 'HTTPS' )) {
			$prot = 'https://';
		} else {
			$prot = 'http://';
		}
		
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		// $path = 'personal/' . $usr->getUsername() . '/files/';
		
		if ($typ != "") {
			$path = str_replace ( '-', '/', $typ ) . '/';
			// $path = $usr->getUsername() . '/' . $typ . '/files/';
			$delete_url = $prot . $this->getRequest ()->server->get ( 'SERVER_NAME' ) . '/auth/security/delpersonal/' . $typ;
		} else {
			$path = 'personal/' . $usr->getUsername () . '/files/';
			$delete_url = $prot . $this->getRequest ()->server->get ( 'SERVER_NAME' ) . '/auth/security/delpersonal';
		}
		
		$url = $prot . $this->getRequest ()->server->get ( 'SERVER_NAME' ) . '/' . $path;
		// $delete_url = $prot . $this->getRequest()->server->get('SERVER_NAME') . '/auth/security/delpersonal';
		$dir = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/' . $path;
		
		$options = array (
				'upload_dir' => $dir,
				'upload_url' => $url,
				'delete_url' => $delete_url 
		);
		$upload_handler = new UploadHandler ( $options );
		// store image
		
		if ($typ != "") {
			return array ();
		}
		
		$filename = $this->getRequest ()->get ( 'file' );
		$em = $this->getDoctrine ()->getManager ();
		$personimage = $em->getRepository ( 'AcmePersonBundle:Personimage' )->findOneByIdPersonFilename ( $usr->getId (), $filename );
		$em->remove ( $personimage );
		$em->flush ();
		
		return array ();
	}
	
	/**
	 * @Route("/updatepersonal/{filename}", name="update_personal")
	 * @Template()
	 */
	public function updatePersonalAction($filename) {
		$em = $this->getDoctrine ()->getManager ();
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		if ($filename == "n_ewfile") {
			if (count ( $em->getRepository ( 'AcmePersonBundle:Personimage' )->findByPerson ( $usr->getId () ) ) > 1) {
				return array ();
			} else {
				$personimages = $em->getRepository ( 'AcmePersonBundle:Personimage' )->findByPerson ( $usr->getId () );
				foreach ( $personimages as $personimage ) {
					$personimage->setStandart ( 1 );
					$em->flush ();
					$this->resizeImage ( $personimage->getImage (), $usr->getUsername (), "profilbild", "200" );
					$this->resizeImage ( $personimage->getImage (), $usr->getUsername (), "pinnwand", "60" );
					return array ();
				}
			}
		}
		
		$personimage = $em->getRepository ( 'AcmePersonBundle:Personimage' )->findOneByIdPersonStandard ( $usr->getId () );
		if ($personimage) {
			$personimage->setStandart ( 0 );
			$em->flush ();
		}
		
		$personimage = $em->getRepository ( 'AcmePersonBundle:Personimage' )->findOneByIdPersonFilename ( $usr->getId (), $filename );
		if (! $personimage) {
			throw $this->createNotFoundException ( 'No Standart set for' . $filename );
		} else {
			$personimage->setStandart ( 1 );
			$em->flush ();
		}
		
		$this->resizeImage ( $filename, $usr->getUsername (), "profilbild", "200" );
		$this->resizeImage ( $filename, $usr->getUsername (), "pinnwand", "60" );
		
		return array ();
	}
	
	/**
	 * @Route("/prepareimage/{filename}", name="prepare_image")
	 * @Template()
	 */
	public function prepareImageAction($filename = "") {
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		$arr_data = explode ( '---___---', $filename );
		
		$path = "";
		foreach ( $arr_data as $key => $data ) {
			if ($key < count ( $arr_data ) - 1) {
				if ($path != "") {
					$path .= $data . '/';
				} else {
					$path = '/' . $data . '/';
				}
			}
		}
		// eintrag in Pinnwand
		$request = $this->getRequest ();
		$text = $request->get ( 'text' );
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$em = $this->getDoctrine ()->getManager ();
		$pinnwands = $em->getRepository ( 'AcmePinnwandBundle:Pinnwand' )->findByImage ( $path );
		if (! $pinnwands) {
			$pinnwand = new Pinnwand ();
			$pinnwand->setText ( $text );
			$pinnwand->setImage ( $path );
			$pinnwand->setCreatedAt ( new \DateTime ( "now" ) );
			$pinnwand->setGroupId ( 0 );
			$user = $em->getRepository ( 'AcmeUserBundle:User' )->find ( $usr->getId () );
			$pinnwand->addUser ( $user );
			$user->addPinnwand ( $pinnwand );
			$em->persist ( $pinnwand );
			$em->flush ();
		} else {
			foreach ( $pinnwands as $pinnwand ) {
				$pinnwand->setText ( $text );
				$em->persist ( $pinnwand );
				$em->flush ();
			}
		}
		
		$this->resizeImage ( $arr_data [count ( $arr_data ) - 1], $usr->getUsername (), "preview", "150", $path );
		$this->resizeImage ( $arr_data [count ( $arr_data ) - 1], $usr->getUsername (), "lightbox", "600", $path );
		exit ();
	}
	
	/**
	 * @Route("/checkdirectory/{directory}", name="check_directory")
	 * @Template()
	 */
	public function checkDirectoryAction($directory = "") {
		$directory = str_replace ( '---___---', '/', $directory );
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . $directory;
		$arr_dir = array ();
		if ($handle = opendir ( $path )) {
			while ( false !== ($file = readdir ( $handle )) ) {
				if (! is_dir ( $path . $file ) && $file != "." && $file != "..") {
					$arr_dir [] = $file;
				}
			}
		}
		
		$em = $this->getDoctrine ()->getManager ();
		if (count ( $arr_dir ) == 0) {
			// delete Datenbank eintrag
			if (preg_match ( '~/pinnwand/~', $directory )) {
				$pinnwands = $em->getRepository ( 'AcmePinnwandBundle:Pinnwand' )->findByImage ( $directory );
				foreach ( $pinnwands as $pinnwand ) {
					try {
						$em->remove ( $pinnwand );
						$em->flush ();
					} catch ( \Doctrine\Orm\NoResultException $e ) {
						$_pinnwand = null;
					}
				}
			}
		} else {
			// Eintrag in Pinnwand
			$request = $this->getRequest ();
			$text = $request->get ( 'text' );
			$pinnwands = $em->getRepository ( 'AcmePinnwandBundle:Pinnwand' )->findByImage ( $directory );
			foreach ( $pinnwands as $pinnwand ) {
				$pinnwand->setText ( $text );
				$em->persist ( $pinnwand );
				$em->flush ();
				echo $pinnwand->getId ();
			}
		}
		
		exit ();
	}
	
	/**
	 * @Route("/testform", name="test_form")
	 * @Template()
	 */
	public function testFormAction() {
		return array ();
	}
	private function resizeImage($filename, $username, $ordner, $newwidth, $path = "") {
		if ($path != "") {
			$dir = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . $path;
		} else {
			$dir = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/personal/' . $username . '/files/';
		}
		
		$dirordner = $dir . $ordner . '/';
		if (! is_dir ( $dirordner )) {
			mkdir ( $dirordner );
		}
		
		list ( $width, $height ) = getimagesize ( $dir . $filename );
		// calulate percent
		$prozent = round ( $newwidth / ($width / 100) );
		
		$newheight = round ( ($height / 100) * $prozent );
		
		$img = imagecreatetruecolor ( $newwidth, $newheight );
		$arr_filename = explode ( ".", $filename );
		if ($arr_filename [count ( $arr_filename ) - 1] == "jpg" || $arr_filename [count ( $arr_filename ) - 1] == "JPG" || $arr_filename [count ( $arr_filename ) - 1] == "jpeg") {
			$source = imagecreatefromjpeg ( $dir . $filename );
			imagecopyresized ( $img, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
			imagejpeg ( $img, $dirordner . $filename, 100 );
		} else if ($arr_filename [count ( $arr_filename ) - 1] == "png" || $arr_filename [count ( $arr_filename ) - 1] == "PNG") {
			$source = imagecreatefrompng ( $dir . $filename );
			imagecopyresized ( $img, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
			imagepng ( $img, $dirordner . $filename, 9 );
		} else if ($arr_filename [count ( $arr_filename ) - 1] == "gif" || $arr_filename [count ( $arr_filename ) - 1] == "GIF") {
			$source = imagecreatefromgif ( $dir . $filename );
			imagecopyresized ( $img, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
			imagegif ( $img, $dirordner . $filename );
		}
	}
	
	/**
	 * @Route("/insertpinw", name="insert_pinnwand")
	 * @Template()
	 */
	public function insertPinnwandAction(Request $request) {
		// get user
		$text = $request->get ( 'pinnwand' );
		$groupid = $request->get ( 'groupid' );
		if (empty ( $text )) {
			return array ();
		}
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$em = $this->getDoctrine ()->getManager ();
		$pinnwand = new Pinnwand ();
		$pinnwand->setText ( $text );
		$pinnwand->setImage ( "" );
		$pinnwand->setCreatedAt ( new \DateTime ( "now" ) );
		$pinnwand->setGroupId ( $groupid );
		$user = $em->getRepository ( 'AcmeUserBundle:User' )->find ( $usr->getId () );
		$pinnwand->addUser ( $user );
		$user->addPinnwand ( $pinnwand );
		$em->persist ( $pinnwand );
		$em->flush ();
		$arr_result = array ();
		$arr_result ["id"] = $pinnwand->getId ();
		$arr_result ["createdat"] = $pinnwand->getCreatedAt ()->format ( 'Y-m-d H:i:s' );
		echo json_encode ( $arr_result );
		
		return array ();
	}
	
	/**
	 * @Route("/sendpinnwand/{id}", name="send_pinnwand")
	 * @Template()
	 */
	public function sendPinnwandMailAction($id = 0) {
		$em = $this->getDoctrine ()->getManager ();
		$pinnwand = $em->getRepository ( 'AcmePinnwandBundle:Pinnwand' )->find ( $id );
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		// $arr_data = $this->getCommonSecurity();
		
		if ($pinnwand->getText () == '' && $pinnwand->getImage () == '') {
			exit ();
		}
		
		$em = $this->getDoctrine ()->getManager ();
		$connection = $em->getConnection ();
		$statement = $connection->prepare ( "
			SELECT p.firstname, p.lastname, p.street, p.postcode, p.city, p.country, p.phoneoffice, p.phonehome, p.mobile, p.email, p.isbookemailsend, IFNULL( pi.path, 'bundles/acmeperson/images/') AS path, IFNULL( pi.image , 'face-std-thumbnail.jpg' ) AS image FROM persons p
   				INNER JOIN user_person up ON p.id = up.person_id
   				INNER JOIN users u ON up.user_id = u.id
    			LEFT JOIN personimages pi ON p.id = pi.person_id AND pi.standart = 1
    			WHERE u.id = " . $usr->getId () );
		$statement->execute ();
		$arr_data = $statement->fetchAll ();
		
		$mailtext = $this->getMailHtml ( $arr_data [0], $pinnwand );
		
		$em = $this->getDoctrine ()->getManager ();
		
		$persons = $em->getRepository ( 'AcmePersonBundle:Person' )->findAll ();
		
		$bcc = "";
		foreach ( $persons as $person ) {
			if ($usr->getEmail () != $person->getEmail ()) {
				if ($person->getIsbookemailsend ()) {
					if ($bcc != '') {
						$bcc .= ', ' . $person->getEmail ();
					} else {
						$bcc = $person->getEmail ();
					}
				}
			}
		}
		
		// f�r HTML-E-Mails muss der 'Content-type'-Header gesetzt werden
		$header = 'MIME-Version: 1.0' . "\r\n";
		$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		
		// zus�tzliche Header
		$header .= 'To: SELV-book <info@eisen-leger.ch>' . "\r\n";
		$header .= 'From: SELV-book <info@eisen-leger.ch>' . "\r\n";
		// $header .= 'Cc: miguel@closas.ch' . "\r\n";
		$header .= 'Bcc: ' . $bcc . "\r\n";
		// verschicke die E-Mail
		mail ( 'info@eisen-leger.ch', $arr_data [0] ['firstname'] . ' ' . $arr_data [0] ['lastname'] . ' hat ins SELV-book geschrieben', $mailtext, $header );
		
		exit ();
	}
	private function getMailHtml($arr_data, $pinnwand) {
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		$html = '
			<html>
			<head>
			  <title>SELV-book</title>
			  <style>
				body { font-family:Arial; margin:0; padding:0; text-align:left;  }
				table { border-collapse:collapse; margin-top:10px;}
				td { padding:5px; font-size:12px; }
				
			  </style>
			</head>
			<body>
			  <table cellspacing=0 cellpadding=0 align="center">
			    <tr>
			      <td style="background-color:#CCCCCC; font-size:14px" colspan="2"><b>SELV-book</b></td>
			    </tr>
    			<tr>
			      <td><a href="' . $this->getRequest ()->getSchemeAndHttpHost () . $this->generateUrl ( 'login_index' ) . '#' . $arr_data ['firstname'] . $pinnwand->getCreatedAt ()->format ( 'Y-m-d H:i:s' ) . '"><img src="' . $this->getRequest ()->getSchemeAndHttpHost () . '/' . $arr_data ['path'] . 'thumbnail/' . $arr_data ['image'] . '" /></a></td>';
		
		if ($pinnwand->getText () != '') {
			$html .= '<td width="600" style="font-weight:bold; font-style:italic;">' . $arr_data ['firstname'] . ' ' . $arr_data ['lastname'] . '<br /><span style="font-weight:normal; font-style:normal;">' . $arr_data ['firstname'] . ' hat geschrieben: "' . nl2br ( $pinnwand->getText () ) . '"</span></td>';
		} else {
			$html .= '<td width="600" style="font-weight:bold; font-style:italic;">' . $arr_data ['firstname'] . ' ' . $arr_data ['lastname'] . '<br /><span style="font-weight:normal; font-style:normal;">' . $arr_data ['firstname'] . ' hat Bilder uploaded !</span></td>';
		}
		
		$html .= '  
			    </tr>
			    <tr>
			      <td style="background-color:#CCCCCC; font-size:10px;" colspan="2">SELV-book &copy; 2015</b></td>
			    </tr>
			   </table>
			</body>
			</html>    			
    			';
		
		return $html;
	}
	
	/**
	 * @Route("/imagedirectory", name="image_directory")
	 * @Template()
	 */
	public function imageDirectoryAction(Request $request) {
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/pinnwand/';
		if (! is_dir ( $path )) {
			mkdir ( $path );
		}
		
		$path = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' ) . '/pinnwand/' . $usr->getUsername () . '/';
		if (! is_dir ( $path )) {
			mkdir ( $path );
		}
		
		$arr_dir = array ();
		if ($handle = opendir ( $path )) {
			while ( false !== ($file = readdir ( $handle )) ) {
				if (is_dir ( $path . $file ) && $file != "." && $file != "..") {
					$arr_dir [] = $file;
				}
			}
		}
		sort ( $arr_dir, SORT_NUMERIC );
		if (count ( $arr_dir ) > 0) {
			$dirname = $arr_dir [count ( $arr_dir ) - 1] + 1;
		} else {
			$dirname = 1;
		}
		$newdir = $dirname . '/';
		if (! is_dir ( $path . $newdir )) {
			mkdir ( $path . $newdir );
		}
		
		$newdir = $newdir . 'files/';
		if (! is_dir ( $path . $newdir )) {
			mkdir ( $path . $newdir );
		}
		
		echo 'pinnwand-' . $usr->getUsername () . '-' . $dirname . '-files';
		return array ();
	}
	
	/**
	 * @Route("/pswchange", name="psw_change")
	 * @Template()
	 */
	public function pswChangeAction() {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'usersinformation' => $arr_data ["usersinformation"] 
		);
	}
	
	/**
	 * @Route("/setpswchange", name="setpsw_change")
	 * @Template()
	 */
	public function setPswChangeAction() {
		$password1 = $this->getRequest ()->get ( 'password1' );
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$em = $this->getDoctrine ()->getManager ();
		$user = $em->getRepository ( 'AcmeUserBundle:User' )->find ( $usr->getId () );
		$user->setPassword ( sha1 ( $password1 ) );
		$em->persist ( $user );
		$em->flush ();
		echo 'Passwort erfolgreich ge�ndert';
		exit ();
	}
	
	/**
	 * @Route("/addresschange", name="address_change")
	 * @Template()
	 */
	public function addressChangeAction() {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'person' => $arr_data ["persons"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'usersinformation' => $arr_data ["usersinformation"] 
		);
	}
	
	/**
	 * @Route("/setperschange", name="setpers_change")
	 * @Template()
	 */
	public function setPersChangeAction() {
		$all_post_params = $this->getRequest ()->request->all ();
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$em = $this->getDoctrine ()->getManager ();
		$person = $em->getRepository ( 'AcmePersonBundle:Person' )->find ( $usr->getId () );
		
		foreach ( $all_post_params as $key => $param ) {
			if ($key == 'email') {
				if ($usr->getEmail () != $param) {
					if (! $em->getRepository ( 'AcmeUserBundle:User' )->findByEmail ( $param )) {
						$usr->setEmail ( $param );
					} else {
						echo 'Du musst eine andere Email nehmen, diese geh�rt bereits einem anderen Benutzer!';
						exit ();
					}
				} else {
					$usr->setEmail ( $param );
				}
				$em->persist ( $usr );
				$em->flush ();
			}
			call_user_func_array ( array (
					$person,
					'set' . ucfirst ( $key ) 
			), array (
					$param 
			) );
		}
		$em->persist ( $person );
		$em->flush ();
		echo 'Daten erfolgreich ge�ndert';
		exit ();
	}
	
	/**
	 * @Route("/phonechange", name="phone_change")
	 * @Template()
	 */
	public function phoneChangeAction() {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'person' => $arr_data ["persons"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'usersinformation' => $arr_data ["usersinformation"] 
		)
		;
	}
	
	/**
	 * @Route("/emailchange", name="email_change")
	 * @Template()
	 */
	public function emailChangeAction() {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'usersinformation' => $arr_data ["usersinformation"] 
		)
		;
	}
	
	/**
	 * @Route("/mottochange", name="motto_change")
	 * @Template()
	 */
	public function mottoChangeAction() {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'usersinformation' => $arr_data ["usersinformation"] 
		)
		;
	}
	
	/**
	 * @Route("/logoutuser", name="logout_user")
	 * @Template()
	 */
	public function logoutuserAction() {
		$user = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$user->setLastActivity ( '0000-00-00 00:00:00' );
		$em = $this->getDoctrine ()->getManager ();
		$em->persist ( $user );
		$em->flush ();
		exit ();
	}
	
	/**
	 * @Route("/areuserslive", name="areusers_live")
	 * @Template()
	 */
	public function areUsersLiveAction() {
		$users = $this->getDoctrine ()->getRepository ( 'AcmeUserBundle:User' )->findAll ();
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$all_users = array ();
		foreach ( $users as $user ) {
			// echo $user->getLastActivity()->format(); exit;
			if ($usr->getId () != $user->getId ()) {
				$person = $this->getDoctrine ()->getRepository ( 'AcmePersonBundle:Person' )->find ( $user->getId () );
				$personimages = $this->getDoctrine ()->getRepository ( 'AcmePersonBundle:Personimage' )->findByPerson ( $user->getId () );
				
				$isStandart = false;
				foreach ( $personimages as $personimage ) {
					if ($personimage->getStandart ()) {
						$all_users ["" . $user->getId ()] ["file"] = '/' . $personimage->getPath () . 'thumbnail/' . $personimage->getImage ();
						$isStandart = true;
					}
				}
				if (! $isStandart) {
					$all_users ["" . $user->getId ()] ["file"] = '/bundles/acmeperson/images/face-std-thumbnail.jpg';
				}
				
				$all_users ["" . $user->getId ()] ["firstname"] = $person->getFirstname ();
				if (time () - strtotime ( $user->getLastActivity ()->format ( 'Y-m-d H:i:s' ) ) <= 120) {
					// aktiv
					$all_users ["" . $user->getId ()] ["status"] = true;
				} else {
					// inaktiv
					$all_users ["" . $user->getId ()] ["status"] = false;
				}
			}
		}
		echo json_encode ( $all_users );
		exit ();
	}
	
	/**
	 * @Route("/userinfo/{id}", name="user_info")
	 * @Template()
	 */
	public function userinfoAction($id = 0) {
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$em = $this->getDoctrine ()->getManager ();
		$connection = $em->getConnection ();
		$statement = $connection->prepare ( "
			SELECT p.firstname, p.lastname, p.street, p.postcode, p.city, p.country, p.phoneoffice, p.phonehome, p.mobile, p.email, p.motto, IFNULL( pi.path, 'bundles/acmeperson/images/') AS path, IFNULL( pi.image , 'face-std.jpg' ) AS image FROM persons p
   				INNER JOIN user_person up ON p.id = up.person_id 
   				INNER JOIN users u ON up.user_id = u.id
    			LEFT JOIN personimages pi ON p.id = pi.person_id AND pi.standart = 1
    			WHERE u.id = " . $id );
		$statement->execute ();
		$arr_data_temp = $statement->fetchAll ();
		$arr_data ["otheruser"] = $arr_data_temp [0];
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'otheruser' => $arr_data ["otheruser"] 
		)
		;
	}
	private function getPinnwand($limitFrom = 0) {
		$usr = $this->container->get ( 'security.context' )->getToken ()->getUser ();
		$em = $this->getDoctrine ()->getManager ();
		$connection = $em->getConnection ();
		$statement = $connection->prepare ( "
			SELECT p.id, p.text, p.image AS piwandpath, p.group_id, p.created_at, up.user_id, pers.firstname, pers.lastname, pers.id AS persid, IFNULL( pi.path, 'bundles/acmeperson/images/') AS path, IFNULL( pi.image , 'face-std.jpg' ) AS image FROM pinnwands p
   				LEFT JOIN user_pinnwand up ON up.pinnwand_id = p.id
   				LEFT JOIN personimages pi ON up.user_id=pi.person_id AND pi.standart=1
    			INNER JOIN persons pers ON up.user_id=pers.id
				group by p.id
				order by p.created_at DESC
    			" );
		$statement->execute ();
		$arr_data = $statement->fetchAll ();
		
		$pinnwands = array ();
		foreach ( $arr_data as $pinnwand ) {
			if ($pinnwand ['piwandpath'] != '') {
				$arr_data ['path'] = $pinnwand ['piwandpath'];
				$arr_data ['apath'] = $this->getRequest ()->server->get ( 'DOCUMENT_ROOT' );
				$arr_data ['base_url'] = $this->getRequest ()->getSchemeAndHttpHost ();
				$imgdatas = new Pinnwandgalerie ( $arr_data );
				$pinnwand ['piwandpath'] = array ();
				$namegal = $pinnwand ['firstname'] . '-' . $pinnwand ['lastname'] . '-' . $pinnwand ['persid'];
				foreach ( $imgdatas->getImages () as $key => $imgdata ) {
					$pinnwand ['piwandpath'] [$key] ['preview'] = $imgdata->getPreview ();
					$pinnwand ['piwandpath'] [$key] ['lightbox'] = $imgdata->getLightbox ();
					$pinnwand ['piwandpath'] [$key] ['file'] = $imgdata->getFile ();
					$pinnwand ['piwandpath'] [$key] ['galeriename'] = "galerie-" . $namegal . "-" . $imgdatas->getId () . "-" . $usr->getId ();
				}
			}
			
			if ($pinnwand ['group_id'] > 0) {
				$pinnwands [$pinnwand ['group_id']] [] = $pinnwand;
			} else {
				$pinnwands [$pinnwand ['id']] [] = $pinnwand;
			}
		}
		krsort ( $pinnwands );
		foreach ( $pinnwands as $key => $pinnwand ) {
			if (count ( $pinnwand ) > 1) {
				$temp_arr = array ();
				foreach ( $pinnwand as $data ) {
					$temp_arr [$data ["id"]] = $data;
				}
				ksort ( $temp_arr );
				$pinnwands [$key] = $temp_arr;
			}
		}
		
		// Limit back
		$_pinnwands = array ();
		$i = 0;
		foreach ( $pinnwands as $pinnwand ) {
			if ($i >= 0 && $i < ($this->limitRange + $limitFrom)) {
				$_pinnwands [] = $pinnwand;
			}
			$i ++;
		}
		
		return $_pinnwands;
	}
	private function getHistoryLink($limitFrom = 0) {
		$em = $this->getDoctrine ()->getManager ();
		$connection = $em->getConnection ();
		$statement = $connection->prepare ( "SELECT COUNT(id) AS rows FROM pinnwands WHERE group_id=0" );
		$statement->execute ();
		$totalRows = $statement->fetchAll ();
		if (($limitFrom + $this->limitRange) < $totalRows [0] ['rows']) {
			return ($limitFrom + $this->limitRange);
		} else {
			return 0;
		}
	}
}